const Base = require('./base.js');
module.exports = class extends Base {
	
	get relation() {
		return {
			rule: {
				type: think.Model.MANY_TO_MANY,
				rModel: 'sys_role_rule',
				model: 'sys_rule',
				rfKey: 'rule_id',
				where: {
					status: 1
				},
				order: {
					sort: 'asc'
				}
			},
			unit: {
				type: think.Model.BELONG_TO,
				model: 'sys_unit',
				key: 'unit_id'

			}
		}
	}

	async menusPermisson(role) {
		let roleIds = [],
			//roleCodes = [],
			userRoles = role || [];
		userRoles.forEach((obj) => {
			roleIds.push(obj.id);
			//roleCodes.push(obj.code);
		});
		let firstMenus = [],
			secondMenus = {},
			permission = [];
		if(roleIds.length > 0) {

			let roles = await this.where({
				id: ['IN', roleIds]
			}).select();
			console.log(roles);

			roles.forEach((role) => {
				//关联关系自动查出角色下的权限
				role.rule.forEach((obj) => {
					obj.role_id = "";
					if(obj.code.split(":").length == 1) {
						if(JSON.stringify(firstMenus).indexOf(JSON.stringify(obj)) < 0 && obj.type == 1) {
							firstMenus.push(obj);

						}

					} else {
						let s = secondMenus[obj.pid] || [];
						if(JSON.stringify(s).indexOf(JSON.stringify(obj)) < 0 && obj.type == 1) {
							s.push(obj);
						}
						secondMenus[obj.pid] = s;
					}
					if(obj.code) {
						permission.push(obj.code);
					}
				});

			});

		}

		return {
			firstMenus: firstMenus,
			secondMenus: secondMenus,
			permission: permission,
			roleIds: roleIds
		};
	}

	async permission(roleids) {
		let firstMenus = [],
			secondMenus = [];
		let roles = await this.where({
			id: ['IN', roleids]
		}).select();

		if(!think.isEmpty(roles)) {

			roles.forEach((role) => {

				role.rule.forEach((obj) => {
					obj.role_id = "";
					obj.hasChildren = obj.hasChildren == 1 ? true : false;
					if(JSON.stringify(firstMenus).indexOf(JSON.stringify(obj)) < 0 && obj.code.split(":").length == 1) {

						firstMenus.push(obj);

					} else {
						if(JSON.stringify(secondMenus).indexOf(JSON.stringify(obj)) < 0) {
							secondMenus.push(obj);
						}

					}

				});

			});
		}
		let data = {
			firstMenus: firstMenus,
			secondMenus: secondMenus
		};
		if(!think.isArray(roleids)) {
			data.role = roles[0];
		}
		return data;

	}
};